package com.sun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.common.Exception.CustomException;
import com.sun.entity.Category;
import com.sun.entity.Drug;
import com.sun.mapper.CategoryMapper;
import com.sun.service.CategoryService;
import com.sun.service.DrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/2/21 17:08
 * @FileName: CategoryServiceImpl
 * @Description: ""
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    DrugService drugService;
    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Drug> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        lambdaQueryWrapper.eq(Drug::getCategoryId, id);
        int count = drugService.count(lambdaQueryWrapper);

        //查询当前分类是否关联了药品，如果已经关联，抛出一个业务异常
        if (count > 0) {
            //已经关联药品，抛出一个业务异常
            throw new CustomException("当前分类下关联了药品，不能删除");
        }
        //正常删除分类
        super.removeById(id);
    }

    @Override
    public Category selectByName(String name) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Category::getName, name);
        Category category = categoryMapper.selectOne(lambdaQueryWrapper);
        return category;
    }
}
